package com.ysd.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.sun.corba.se.spi.orbutil.fsm.State;
import com.ysd.entity.Userinfo;
import com.ysd.util.DBManager;

public class UserinfoDaoimpl {
	/**
	 * 项数据库添加一条内容
	 * @param user
	 * @return
	 */
	public int addUserinfo(Userinfo user) {
		return DBManager.executeUpdate("insert into userinfo (username,phone,email,content,time,zhuangtai) values('"+user.getUsername()+"','"+user.getPhone()+"','"+user.getEmail()+"','"+user.getContent()+"','"+user.getTime()+"',+'"+user.getZhuangtai()+"')");
	}
	/**
	 * 查询出数据库所有的数据
	 * @return
	 */
	public ArrayList<Userinfo> getLiuYan(int page,int size){
		Connection conn=DBManager.getConnection();
		 ArrayList<Userinfo> list=new ArrayList<Userinfo>();
		 Statement st=null;
		 ResultSet rs=null;
		try {
			 st=conn.createStatement();
			 rs =st.executeQuery("SELECT * FROM userinfo LIMIT "+(page-1)*size+","+size);
			while(rs.next()) {
				String username=rs.getString("username");
				String phone=rs.getString("phone");
				String email=rs.getString("email");
				String content=rs.getString("content");
				int userId=rs.getInt("userId");
				String time=rs.getString("time");
				String zhuangtai=rs.getString("zhuangtai");
				Userinfo u=new Userinfo(userId, username, phone, email, content,time,zhuangtai);
				list.add(u);
			}
			return list;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}finally {
			DBManager.closeAll(conn, st, rs);
		}
		
	}
	
	public ArrayList<Userinfo> getLiuYanSize(){
		Connection conn=DBManager.getConnection();
		 ArrayList<Userinfo> list=new ArrayList<Userinfo>();
		 Statement st=null;
		 ResultSet rs=null;
		try {
			 st=conn.createStatement();
			 rs =st.executeQuery("SELECT userId FROM userinfo ");
			while(rs.next()) {
				
				int userId=rs.getInt("userId");
				
				Userinfo u=new Userinfo(userId);
				list.add(u);
			}
			return list;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}finally {
			DBManager.closeAll(conn, st, rs);
		}
		
	}
	
	/**
	 * 根据id删除留言信息
	 * @param id
	 * @return
	 */
	public int delLiuYan(int id) {
		return DBManager.executeUpdate("delete from userinfo WHERE userId="+id);
	}
	
	
	/**
	 * 修改留言信息
	 * @param user
	 * @return
	 */
	public int liuYan_edit(Userinfo user) {
		String zt=user.getZhuangtai();
		if(zt.equals("已读")) {
			 zt="未读";
		} else {
			zt="已读";
		}
		
		return DBManager.executeUpdate("UPDATE userinfo set zhuangtai='"+zt+"' where userId="+user.getUserId());
	}
}
